package org.termine.jsf;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

import org.termine.entity.Location;
import org.termine.entity.PersonalData;
import org.termine.logic.PersonalDataManager;

@ManagedBean
@ViewScoped
public class RegisterJSF extends BaseJSF implements Serializable {

	private static final long serialVersionUID = -3165683647937755679L;
	
	private PersonalData personalData;
	private Location location;
	private String confirmPassword;
	private boolean registerAsProvider;
	
	@ManagedProperty(value = "#{personalDataManager}")
	private PersonalDataManager personalDataManager;
	@ManagedProperty(value = "#{loginJSF}")
	private LoginJSF loginJSF;

	/*
	 * Init
	 */
	@PostConstruct
	public void init() {
		location = new Location();
		personalData = new PersonalData();
		confirmPassword = "";
		registerAsProvider = false;
	}

	/*
	 * Jsf Action Methods
	 */
	public String performRegister() {
		if (personalData.getPassword().equals(confirmPassword)) {
			if (registerAsProvider) {
				if (getPersonalDataManager().addProvider(personalData, location)) {
					getLoginJSF().setWhoAmI("PROVIDER");
					getLoginJSF().setPersonalData(personalData);
					getLoginJSF().setLocation(location);
//					init();
					setInfoMessage("Registered successfully!");
					return "PROVIDER";
				}
			} else {
				if (getPersonalDataManager().addClient(personalData, location)) {
					setInfoMessage("Registered successfully!");
					getLoginJSF().setWhoAmI("CLIENT");
					getLoginJSF().setPersonalData(personalData);
					getLoginJSF().setLocation(location);
//					init();
					return "CLIENT";
				}
			}
		}
		setErrorMessage("registering failed");
		return "ERROR";
	}

	/*
	 * Getters & Setters
	 */
	public PersonalDataManager getPersonalDataManager() {
		return personalDataManager;
	}

	public void setPersonalDataManager(PersonalDataManager personalDataManager) {
		this.personalDataManager = personalDataManager;
	}

	public LoginJSF getLoginJSF() {
		return loginJSF;
	}

	public void setLoginJSF(LoginJSF loginJSF) {
		this.loginJSF = loginJSF;
	}
	
	public PersonalData getPersonalData() {
		return personalData;
	}

	public Location getLocation() {
		return location;
	}

	public void setLocation(Location location) {
		this.location = location;
	}

	public void setPersonalData(PersonalData personalData) {
		this.personalData = personalData;
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public boolean isRegisterAsProvider() {
		return registerAsProvider;
	}

	public void setRegisterAsProvider(boolean registerAsProvider) {
		this.registerAsProvider = registerAsProvider;
	}
}
